package services;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.DateFormat;
import java.util.Date;
import java.util.Properties;

import model.Client;
import model.Payment;
import model.Product;

import org.apache.axis2.context.MessageContext;

import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.CannedAccessControlList;
import com.amazonaws.services.s3.model.PutObjectRequest;


public class StorageService 
{
	private static Statement stmt;
    private static Connection conn;
    
    protected final String bucketName = "hwcbsoft";
    
    public StorageService()
    { /* Empty */ }
    
    
    public boolean storeDatabase(Client c, Product p)
	{
		String sql = "";
		
		Payment payment = new Payment();
		try
		{
			payment.setClient(c);
			payment.setIdPurchase(p.getProductId());
			payment.setCreditCard(c.getCreditNumber());
			payment.setValue(p.getValue());
			
			sql = "INSERT INTO payment (paymentClientID, paymentProductID, paymentDate, paymentValue) " +
				  "VALUES ('" + payment.getClient().getClientId() + "', '" + payment.getIdPurchase() + "', '" +
				  DateFormat.getInstance().format(new Date(System.currentTimeMillis())) + "', '" + payment.getValue() + "')";
			getStatement().execute(sql);
			
			return true;
		}
		catch (SQLException ex)
		{ ex.printStackTrace(); }
		
		return false;
	}
    
    
    public boolean storeFileLocal(Client c, Product p)
	{
		String conteudo = "";
		
		Payment payment = new Payment();
		try
		{
			payment.setClient(c);
			payment.setIdPurchase(p.getProductId());
			payment.setCreditCard(c.getCreditNumber());
			payment.setValue(p.getValue());
			
			conteudo += "Dados da compra:" + "\n";
			conteudo += "ID do cliente: " + payment.getClient().getClientId() + "\n";
			conteudo += "ID da compra: " + payment.getIdPurchase() + "\n";
			conteudo += "Data de pagamento: " + DateFormat.getInstance().format(new Date(System.currentTimeMillis())) + "\n";
			conteudo += "Valor pago: " + payment.getValue();
			
			String nomeArquivo = payment.getIdPurchase() + ".txt";
			File f = new File(nomeArquivo);
	        PrintWriter pw = new PrintWriter(f);
	        pw.write(conteudo);
	        pw.close();
			
			return true;
		}
		catch (IOException ex)
		{ ex.printStackTrace(); }
		
		return false;
	}

    
	public boolean storeFileCloud(Client c, Product p)
	{
		String conteudo = "";
		
		Payment payment = new Payment();
		try
		{
			payment.setClient(c);
			payment.setIdPurchase(p.getProductId());
			payment.setCreditCard(c.getCreditNumber());
			payment.setValue(p.getValue());
			
			conteudo += "Dados da compra:" + "\n";
			conteudo += "ID do cliente: " + payment.getClient().getClientId() + "\n";
			conteudo += "ID da compra: " + payment.getIdPurchase() + "\n";
			conteudo += "Data de pagamento: " + DateFormat.getInstance().format(new Date(System.currentTimeMillis())) + "\n";
			conteudo += "Valor pago: " + payment.getValue();
			
			String nomeArquivo = payment.getIdPurchase() + ".txt";
			File f = new File(nomeArquivo);
	        PrintWriter pw = new PrintWriter(f);
	        pw.write(conteudo);
	        pw.close();
	        
	        MessageContext msg = MessageContext.getCurrentMessageContext();
	        String accessKey = (String)msg.getParameter("accessKey").getValue();
	        String secretKey = (String)msg.getParameter("secretKey").getValue();
	        
	        // Properties properties = new Properties();
	     	// FileInputStream input = new FileInputStream("AwsCredentials.properties");
	     	// properties.load(input);
	     	// input.close();
	     						
	     	// String accessKey = properties.getProperty("accessKey");
	     	// String secretKey = properties.getProperty("secretKey");
			
			BasicAWSCredentials credentials = new BasicAWSCredentials(accessKey, secretKey);
			AmazonS3 S3 = new AmazonS3Client(credentials);
			PutObjectRequest por = new PutObjectRequest(bucketName, nomeArquivo, f);
			por.setCannedAcl(CannedAccessControlList.PublicRead);
			S3.putObject(por);
			
			f.delete();
			return true;
		}
		catch (Exception ex)
		{ ex.printStackTrace(); 
			return false;
		}
		
		
	}
	
	
	private static Statement getStatement()
	{
		if (stmt != null)
			return stmt;
			
		try
		{
			MessageContext msg = MessageContext.getCurrentMessageContext();
			String url = (String)msg.getParameter("jdbc.url").getValue();
			String user = (String)msg.getParameter("jdbc.user").getValue();
			String password = (String)msg.getParameter("jdbc.pwd").getValue();
			
			// Properties properties = new Properties();
			// FileInputStream input = new FileInputStream("database.properties");
			// properties.load(input);
			// input.close();
				
			// String url = properties.getProperty("jdbc.url");
			// String user = properties.getProperty("jdbc.user");
			// String password = properties.getProperty("jdbc.pwd");
	        
	        Class.forName("com.mysql.jdbc.Driver");
			conn = DriverManager.getConnection(url, user, password);
			stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
		}
		catch (ClassNotFoundException ex) 
		{ System.out.println("Driver JDBC-ODBC nao encontrado"); }
		catch (SQLException ex) 
		{ System.out.println("Erro: " + ex.getMessage()); } 
		catch (Exception e) 
		{ System.out.println("Erro: " + e.getMessage()); }

	    return stmt;
	}
}
